package com.outsourcing.bottle.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aviary.android.feather.Constants;
import com.aviary.android.feather.FeatherActivity;
import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.domain.AvatarEntry;
import com.outsourcing.bottle.domain.BottleFeedInfo;
import com.outsourcing.bottle.domain.FriendFeedEntry;
import com.outsourcing.bottle.domain.FriendFeedInfo;
import com.outsourcing.bottle.domain.FriendGroupEntry;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.ProfileEntry;
import com.outsourcing.bottle.domain.ProfileInfo;
import com.outsourcing.bottle.domain.ResponseResult;
import com.outsourcing.bottle.domain.SpaceBottleFeedEntry;
import com.outsourcing.bottle.domain.SpaceEntry;
import com.outsourcing.bottle.domain.SpaceInfo;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.remoteimage.RemoteImageView;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ImageLoader;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.util.Utility;
import com.outsourcing.bottle.widget.CustomListView;
/**
 * 
 * @author 06peng
 *
 */
@SuppressLint({ "ResourceAsColor", "ResourceAsColor", "ResourceAsColor" })
public class UserSpaceActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener {

	private final int get_space_info = 1;
	private final int get_space_info_success = 2;
	private final int cancel_friend = 3;
	private final int cancel_friend_success = 4;
	private final int set_friend_group = 5;
	private final int set_friend_group_success = 6;
	private final int error = 0;
	private final int exchange_profile = 7;
	private final int get_more_data = 9;
	private final int check_friend_error = 10;
	private final int add_friend_success = 11;
	private final int get_newsfeeds = 12;
	private final int get_bottlefeeds = 13;
	private final int get_profile = 14;
	private final int refresh_space_info = 15;
	private final int set_blacklist = 16;
	private final int set_default_avatar = 17;
	private final int activity_result_camara_with_data = 1006;
	private final int activity_result_pick_with_data = 18;
	private final int set_avatar = 19;
	private final int view_album_error = 20;
	private final int user_baseinfo_notfull = 21;
	private final int complete_info = 22;
	
	private static final int EXEU_CHECK_FRIEND_FAILED = 23;
	private static final int EXEU_CAN_NOT_ADD_FRIEND = 24;
	private static final int EXEU_CHECK_FRIEND_SUCCESS = 25;
	private static final int EXEU_CHECK_FRIEND = 26;
	private static final int EXEU_ALLOW_ADD_FRIEND = 27;
	private static final int activity_result_aviary = 28;
	
	private int ouid;
	private SpaceEntry entry; //用户空间信息
	private List<AvatarEntry> avatarEntries; //用户头像列表
	private ProfileEntry profileEntry; //用户档案
	private List<SpaceBottleFeedEntry> bottleFeedList; //瓶子动态列表
	private List<SpaceBottleFeedEntry> moreBottleFeedList;
	private List<FriendFeedEntry> friendFeedList; //好友动态列表
	private List<FriendFeedEntry> moreFriendFeedList;
	private Handler handler;
	private Bitmap bitmap; //用户头像
	private int space_type;
	private int info_visible;
	private int refresh_type = 0; //1调用updateExchange //2调用updateAvatars
	
	private AvatarEntry entry1;
	private AvatarEntry entry2;
	private AvatarEntry entry3;
	private AvatarEntry entry4;
	private Bitmap bitMap;
	private File picFile;
	public final static int REQUEST_WIDTH = 600;
	private int avatarid;
	
	private List<FriendGroupEntry> groupList;
	private String[] groupNames;
	private int groupItem;
	private int groupId;
	private int count = 10;
	
	/**
	 *  底部按钮的点击类型0：newsfeeds；1：bottlefeeds；2：profile
	 */
	private int selectType = 0;
	NewsFeedAdapter newsAdapter;
	BottlesFeedAdapter bottlesAdapter;
	
	/******* 用户资料 *********/
	private ImageView backView;
	private TextView titleText;
	private TextView titleView;
	private ImageView avatarView;
	private TextView nicknameView;
	private TextView memoView;
	private ImageView sexView;
	private TextView doingView;
	private TextView addressView;
	private ImageView homeView;
//	private ImageView settingView;
	private ImageView editMemoView;

	/***** 设置用户头像 *******/
	private RemoteImageView userAvatar1;
	private ImageView userAvatarBg1;
	private RemoteImageView userAvatar2;
	private ImageView userAvatarBg2;
	private RemoteImageView userAvatar3;
	private ImageView userAvatarBg3;
	private RemoteImageView userAvatar4;
	private ImageView userAvatarBg4;
	private ImageLoader loader;
	
	/******** 交换档案后才能看到Ta的档案 *************/
	private Button btnExchange;
	private Button btnInfoExchange;
	
	/******** 用户积分经验等级 *************/
	private TextView tvCreateAndExp;
	private TextView tvTTCreateAndTTExp;
	private TextView tvLevel;
	private Button upgrade;
	
	/********* 添加好友、交换资料、交换照片、加入黑名单  **************/
	private Button btnAddFriend;
	private Button btnExProfile;
	private Button btnExPhoto;
	private Button btnBlacklist;
	
	/********* 好友动态、瓶子动态、好友档案  **************/
	private Button btnNewsfeeds;
	private Button btnBottlefeeds;
	private Button btnProfile;

	private CustomListView listView;
//	private ProgressBar progressBar;
//	private TextView loadMoreView;
	private View loadMoreView;
	private ImageView menuView;
	
	
	private int visibleLastIndex = 0; // 最后的可视项索引
	public int visibleItemCount; // 当前窗口可见项总数
	
	private View contentView;
	private LinearLayout bodyLayout;
//	private CustomScrollListView listView
	
	private int newsfeedsPage = 1;
	private int bottlefeedsPage = 1;
	
	private String choices[];
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		loader = new ImageLoader(this, AppContext.BottleTimelineIcon);
		setContentView(R.layout.user_space_scrollview);
		ouid = getIntent().getIntExtra("ouid", 0);
		initWidget();
		initUserAvatars();
		initUserIntegral();
		initExchangeButton();
		initFeeds();
		UICore.eventTask(this, this, get_space_info, "get_space_info", null);
	}
	
	private void initWidget() {
		homeView = (ImageView) findViewById(R.id.topbar_menu);
		homeView.setOnClickListener(this);
		menuView = (ImageView) findViewById(R.id.menu);
		menuView.setOnClickListener(this);
//		settingView = (ImageView) findViewById(R.id.topbar_setting);
//		settingView.setOnClickListener(this);
		backView = (ImageView) findViewById(R.id.topbar_back);
		backView.setOnClickListener(this);
		titleView = (TextView) findViewById(R.id.user_space_title);
		titleView.setOnClickListener(this);
		titleText = (TextView) findViewById(R.id.topbar_title);
		listView = (CustomListView) findViewById(R.id.refresh_view);
		listView.setonRefreshListener(new CustomListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				UICore.eventTask(UserSpaceActivity.this, UserSpaceActivity.this, refresh_space_info, null, null);
			}
		});
		listView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				BaseAdapter adapter = null;
				if (selectType == 0) {
					adapter = newsAdapter;
				} else if (selectType == 1) {
					adapter = bottlesAdapter;
				}
				if (adapter != null) {
					int itemsLastIndex = adapter.getCount() + 2; // 数据集最后一项的索引
					int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项 和 head项
					System.out.println(">>>>>>>> itemsLastIndex:" + itemsLastIndex);
					System.out.println(">>>>>>>> lastIndex" + lastIndex);
					if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {
						// 如果是自动加载,可以在这里放置异步加载数据的代码
						System.out.println(">>>>>>>> load more <<<<<<<<<");
						loadMoreView.setVisibility(View.VISIBLE);
						UICore.eventTask(UserSpaceActivity.this, UserSpaceActivity.this, get_more_data, null, null);
					}
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				listView.setFirstVisiableItem(firstVisibleItem);
				UserSpaceActivity.this.visibleItemCount = visibleItemCount;
				visibleLastIndex = firstVisibleItem + visibleItemCount;
			}
		});
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				BaseAdapter adapter = null;
				if (selectType == 0) {
					adapter = newsAdapter;
				} else if (selectType == 1) {
					adapter = bottlesAdapter;
				}
				if (adapter != null) {
					if (arg2 == adapter.getCount() + 2) {
						return;
					} 
					if (selectType == 0) {
						choices = null;
						final FriendFeedEntry entry = friendFeedList.get(arg2 - 2);
						if (entry.getFeed_picid() != 0) {
							if (entry.getFeed_picid() != 0 && entry.getFeed_related_uid() != 0) {
								choices = new String[2];
								choices[0] = getString(R.string.user_space_bottle_view_photo);
								choices[1] = getString(R.string.user_info_view) + entry.getFeed_related_nickname() + getString(R.string.user_info_space);
								chooseAction(choices, entry);
							} else if (entry.getFeed_picid() != 0) {
								choices = new String[1];
								choices[0] = getString(R.string.user_space_bottle_view_photo);
								chooseAction(choices, entry);
							} else if (entry.getFeed_related_uid() != 0) {
								if (TextUtil.notEmpty(entry.getFeed_related_nickname())) {
									choices = new String[1];
									choices[0] = getString(R.string.user_info_view) + entry.getFeed_related_nickname() + getString(R.string.user_info_space);
									chooseAction(choices, entry);
								}
							}
						} else {
							if (entry.getFeed_related_uid() != 0) {
								if (TextUtil.notEmpty(entry.getFeed_related_nickname())) {
									choices = new String[1];
									choices[0] = getString(R.string.user_info_view) + entry.getFeed_related_nickname() + getString(R.string.user_info_space);
									chooseAction(choices, entry);
								}
							}
						}
					} else if (selectType == 1) {
						SpaceBottleFeedEntry entry = bottleFeedList.get(arg2 - 2);
						Intent intent = new Intent(UserSpaceActivity.this, BottleSingleActivity.class);
						intent.putExtra("btid", entry.getBtid());
						startActivity(intent);
					}
				}
			}
		});
		contentView = LayoutInflater.from(this).inflate(R.layout.user_space, null);
		listView.addHeaderView(contentView);
		
		loadMoreView = LayoutInflater.from(this).inflate(R.layout.refreshable_list_footer, null);
		loadMoreView.setVisibility(View.GONE);
		listView.addFooterView(loadMoreView);
		
		bodyLayout = (LinearLayout) contentView.findViewById(R.id.user_space_bodylayout);
		
		avatarView = (ImageView) contentView.findViewById(R.id.user_space_avatar);
		avatarView.setOnClickListener(this);
		nicknameView = (TextView) contentView.findViewById(R.id.user_space_nickname);
		memoView = (TextView) contentView.findViewById(R.id.user_space_memo);
		sexView = (ImageView) contentView.findViewById(R.id.user_space_sex);
		doingView = (TextView) contentView.findViewById(R.id.user_space_doing);
		addressView = (TextView) contentView.findViewById(R.id.user_space_address);
		editMemoView = (ImageView) findViewById(R.id.user_space_edit_memo);
		editMemoView.setOnClickListener(this);
		
		btnExchange = (Button) contentView.findViewById(R.id.user_space_excange);
		btnExchange.setOnClickListener(this);
	}
	
	private void initUserAvatars() {
		userAvatar1 = (RemoteImageView) contentView.findViewById(R.id.user_space_useravatar1);
		userAvatar1.setOnClickListener(this);
		userAvatarBg1 = (ImageView) contentView.findViewById(R.id.user_space_useravatar_bg1);
		
		userAvatar2 = (RemoteImageView) contentView.findViewById(R.id.user_space_useravatar2);
		userAvatar2.setOnClickListener(this);
		userAvatarBg2 = (ImageView) contentView.findViewById(R.id.user_space_useravatar_bg2);
		
		userAvatar3 = (RemoteImageView) contentView.findViewById(R.id.user_space_useravatar3);
		userAvatar3.setOnClickListener(this);
		userAvatarBg3 = (ImageView) contentView.findViewById(R.id.user_space_useravatar_bg3);
		
		userAvatar4 = (RemoteImageView) contentView.findViewById(R.id.user_space_useravatar4);
		userAvatar4.setOnClickListener(this);
		userAvatarBg4 = (ImageView) contentView.findViewById(R.id.user_space_useravatar_bg4);
	}
	
	private void initUserIntegral() {
		tvCreateAndExp = (TextView) contentView.findViewById(R.id.user_info_credit_and_experience_value);
		tvTTCreateAndTTExp = (TextView) contentView.findViewById(R.id.user_info_ttcredit_and_ttenperience_value);
		tvLevel = (TextView) contentView.findViewById(R.id.user_info_level_value);
		upgrade = (Button) contentView.findViewById(R.id.user_info_upgrade);
		upgrade.setOnClickListener(this);
	}
	
	private void initExchangeButton() {
		btnAddFriend = (Button) contentView.findViewById(R.id.user_space_addfriend);
		btnAddFriend.setOnClickListener(this);
		btnExProfile = (Button) contentView.findViewById(R.id.user_space_exprofile);
		btnExProfile.setOnClickListener(this);
		btnExPhoto = (Button) contentView.findViewById(R.id.user_space_exphoto);
		btnExPhoto.setOnClickListener(this);
		btnBlacklist = (Button) contentView.findViewById(R.id.user_space_blacklist);
		btnBlacklist.setOnClickListener(this);
	}
	
	private void initFeeds() {
		btnNewsfeeds = (Button) contentView.findViewById(R.id.user_space_newsfeeds);
		btnNewsfeeds.setOnClickListener(this);
		btnBottlefeeds = (Button) contentView.findViewById(R.id.user_space_bottlefeeds);
		btnBottlefeeds.setOnClickListener(this);
		btnProfile = (Button) contentView.findViewById(R.id.user_space_profile);
		btnProfile.setOnClickListener(this);
	}
	
	private void updateUI() {
		if (entry == null) {
			return;
		}
		info_visible = entry.getInfo_visible();
		space_type = entry.getSpace_type();
		
		((LinearLayout) contentView.findViewById(R.id.user_space_layout)).setVisibility(View.VISIBLE);
		updateUserBaseInfo();
		if (space_type != 3) {
			 updateRelation();
		}
		updateIntegral();
		updateExchange();
		updateFeeds();
		updateAvatarList();
	}
	
	private void updateUserBaseInfo() {
		titleText.setText(entry.getNickname());
		nicknameView.setText(entry.getNickname());
		if (entry.getSex() == 1) {
			sexView.setBackgroundResource(R.drawable.male);
		} else if (entry.getSex() == 2) {
			sexView.setBackgroundResource(R.drawable.female);
		}
		if (TextUtil.notEmpty(entry.getMemo())) {
			((TextView) contentView.findViewById(R.id.user_space_memo)).setVisibility(View.VISIBLE);
			memoView.setText("-" + entry.getMemo());
		} else {
			((TextView) contentView.findViewById(R.id.user_space_memo)).setVisibility(View.GONE);
			memoView.setVisibility(View.GONE);
		}
		if (TextUtil.notEmpty(entry.getCity()) &&  TextUtil.notEmpty(entry.getCountry())) {
			addressView.setVisibility(View.VISIBLE);
			if (AppContext.language == 1) {
				addressView.setText(getString(R.string.user_from) + entry.getCountry() + " " + entry.getCity());
			} else {
				addressView.setText(getString(R.string.user_from) + entry.getCity() + " " + entry.getCountry());
			}
		} else {
			addressView.setVisibility(View.GONE);
		}
		String html = "<font color=black>"+getString(R.string.user_info_doing)+"</font>";
		doingView.setText(Html.fromHtml(html + TextUtil.htmlEncode(entry.getDoing())));
		
		if (bitmap != null) {
			avatarView.setImageBitmap(bitmap);
		}
		if (info_visible == 1) {
			btnExchange.setVisibility(View.GONE);
			avatarView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					byte[] tempBytes = null;
					try {
						tempBytes = ServiceUtils.BitmapTobytes(bitmap);
					} catch (Exception e) {
						e.printStackTrace();
					}
					Intent bigPicIntent = new Intent(UserSpaceActivity.this, PhotoDetailActivity.class);
					bigPicIntent.putExtra("pic_big", entry.getAvatar());
					bigPicIntent.putExtra("thumbnail", tempBytes);
					startActivity(bigPicIntent);
				}
			});
		} else {
			btnExchange.setVisibility(View.VISIBLE);
		}
		String type = null;
		if (space_type == 0) {
			type = getString(R.string.user_space_friend);
			type = getString(R.string.user_space_friend) + "(" + entry.getGroupname() + ")";
		} else if (space_type == 1) {
			type = getString(R.string.user_space_btfriend);
			titleView.setCompoundDrawables(null, null, null, null);
		} else if (space_type == 2) {
			type = getString(R.string.user_space_stranger);
			titleView.setCompoundDrawables(null, null, null, null);
		} else {
			type = getString(R.string.user_space_my);
			titleView.setCompoundDrawables(null, null, null, null);
		}
		titleView.setText(type);
		if (space_type == 3) {
			editMemoView.setVisibility(View.GONE);
//			settingView.setVisibility(View.GONE);
		} else {
			editMemoView.setVisibility(View.VISIBLE);
//			settingView.setVisibility(View.VISIBLE);
		}
	}
	
	private void updateRelation() {
		if (entry.getRelation_twitter() != null && !entry.getRelation_twitter().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_twitter_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_twitter_textview)).setText(entry.getRelation_twitter());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_twitter_layout)).setVisibility(View.GONE);
		}
		if (entry.getRelation_facebook() != null && !entry.getRelation_facebook().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_facebook_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_facebook_textview)).setText(entry.getRelation_facebook());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_facebook_layout)).setVisibility(View.GONE);
		}
		if (entry.getRelation_sina() != null && !entry.getRelation_sina().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_weibo_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_weibo_textview)).setText(entry.getRelation_sina());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_weibo_layout)).setVisibility(View.GONE);
		}
		if (entry.getRelation_tqq() != null && !entry.getRelation_tqq().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_tencent_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_tencent_textview)).setText(entry.getRelation_tqq());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_tencent_layout)).setVisibility(View.GONE);
		}
		if (entry.getRelation_renren() != null && !entry.getRelation_renren().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_renren_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_renren_textview)).setText(entry.getRelation_renren());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_renren_layout)).setVisibility(View.GONE);
		}
		if (entry.getRelation_douban() != null && !entry.getRelation_douban().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_douban_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_douban_textview)).setText(entry.getRelation_douban());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_douban_layout)).setVisibility(View.GONE);
		}
		if (entry.getRelation_qq() != null && !entry.getRelation_qq().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_qq_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_qq_textview)).setText(entry.getRelation_qq());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_qq_layout)).setVisibility(View.GONE);
		}
		if (entry.getRelation_schoolmate() != null && !entry.getRelation_schoolmate().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_school_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_school_textview)).setText(entry.getRelation_schoolmate());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_school_layout)).setVisibility(View.GONE);
		}
		if (entry.getRelation_sameresidecity() != null && !entry.getRelation_sameresidecity().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_samecity_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_samecity_textview)).setText(entry.getRelation_sameresidecity());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_samecity_layout)).setVisibility(View.GONE);
		}
		if (entry.getRelation_samebirthcity() != null && !entry.getRelation_samebirthcity().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_samebirthcity_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_samebirthcity_textview)).setText(entry.getRelation_samebirthcity());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_samebirthcity_layout)).setVisibility(View.GONE);
		}
		if (entry.getRelation_sameworkcity() != null && !entry.getRelation_sameworkcity().equals("")) {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_sameworkcity_layout)).setVisibility(View.VISIBLE);
			((TextView) contentView.findViewById(R.id.user_space_relation_sameworkcity_textview)).setText(entry.getRelation_sameworkcity());
		} else {
			((LinearLayout) contentView.findViewById(R.id.user_space_relation_sameworkcity_layout)).setVisibility(View.GONE);
		}
	}
	
	private void updateAvatarList() {
		int size = 0;
		if (avatarEntries != null && !avatarEntries.isEmpty()) {
			size = avatarEntries.size();
			contentView.findViewById(R.id.user_space_useravatars_layout).setVisibility(View.VISIBLE);
		} else {
			contentView.findViewById(R.id.user_space_useravatars_layout).setVisibility(View.GONE);
		}
		if (size >= 1) {
			entry1 = avatarEntries.get(0);
			if (entry1 != null) {
				contentView.findViewById(R.id.user_space_useravatar1_layout).setVisibility(View.VISIBLE);
				if (entry1.getAvatar_mode() == 1) {
					userAvatar1.setImageUrl(entry1.getAvatar_middlepic());
					userAvatarBg1.setBackgroundResource(R.drawable.frame_avatar1_bg);
				} else if (entry1.getAvatar_mode() == 2) {
					userAvatar1.setImageUrl(entry1.getAvatar_middlepic());
					userAvatarBg1.setBackgroundResource(R.drawable.frame_avatar2_bg);
				} else if (entry1.getAvatar_mode() == 3) {
					userAvatar1.setImageResource(R.drawable.frame_avatar3_lock);
					userAvatarBg1.setBackgroundResource(R.drawable.frame_avatar1_bg);
				} else if (entry1.getAvatar_mode() == 4) {
					userAvatar1.setImageResource(R.drawable.frame_avatar4_add);
					userAvatarBg1.setBackgroundResource(R.drawable.frame_avatar1_bg);
				}
			}
		} else {
			contentView.findViewById(R.id.user_space_useravatar1_layout).setVisibility(View.INVISIBLE);
		}
		
		if (size >= 2) {
			entry2 = avatarEntries.get(1);
			if (entry2 != null) {
				contentView.findViewById(R.id.user_space_useravatar2_layout).setVisibility(View.VISIBLE);
				if (entry2.getAvatar_mode() == 1) {
					userAvatar2.setImageUrl(entry2.getAvatar_middlepic());
					userAvatarBg2.setBackgroundResource(R.drawable.frame_avatar1_bg);
				} else if (entry2.getAvatar_mode() == 2) {
					userAvatar2.setImageUrl(entry2.getAvatar_middlepic());
					userAvatarBg2.setBackgroundResource(R.drawable.frame_avatar2_bg);
				} else if (entry2.getAvatar_mode() == 3) {
					userAvatar2.setImageResource(R.drawable.frame_avatar3_lock);
					userAvatarBg2.setBackgroundResource(R.drawable.frame_avatar1_bg);
				} else if (entry2.getAvatar_mode() == 4) {
					userAvatar2.setImageResource(R.drawable.frame_avatar4_add);
					userAvatarBg2.setBackgroundResource(R.drawable.frame_avatar1_bg);
				}
			}
		}  else {
			contentView.findViewById(R.id.user_space_useravatar2_layout).setVisibility(View.INVISIBLE);
		}
		
		if (size >= 3) {
			entry3 = avatarEntries.get(2);
			if (entry3 != null) {
				contentView.findViewById(R.id.user_space_useravatar3_layout).setVisibility(View.VISIBLE);
				if (entry3.getAvatar_mode() == 1) {
					userAvatar3.setImageUrl(entry3.getAvatar_middlepic());
					userAvatarBg3.setBackgroundResource(R.drawable.frame_avatar1_bg);
				} else if (entry3.getAvatar_mode() == 2) {
					userAvatar3.setImageUrl(entry3.getAvatar_middlepic());
					userAvatarBg3.setBackgroundResource(R.drawable.frame_avatar2_bg);
				} else if (entry3.getAvatar_mode() == 3) {
					userAvatar3.setImageResource(R.drawable.frame_avatar3_lock);
					userAvatarBg3.setBackgroundResource(R.drawable.frame_avatar1_bg);
				} else if (entry3.getAvatar_mode() == 4) {
					userAvatar3.setImageResource(R.drawable.frame_avatar4_add);
					userAvatarBg3.setBackgroundResource(R.drawable.frame_avatar1_bg);
				}
			}
		} else {
			contentView.findViewById(R.id.user_space_useravatar3_layout).setVisibility(View.INVISIBLE);
		}
		
		if (size == 4) {
			entry4 = avatarEntries.get(3);
			if (entry4 != null) {
				contentView.findViewById(R.id.user_space_useravatar4_layout).setVisibility(View.VISIBLE);
				if (entry4.getAvatar_mode() == 1) {
					userAvatar4.setImageUrl(entry4.getAvatar_middlepic());
					userAvatarBg4.setBackgroundResource(R.drawable.frame_avatar1_bg);
				} else if (entry4.getAvatar_mode() == 2) {
					userAvatar4.setImageUrl(entry4.getAvatar_middlepic());
					userAvatarBg4.setBackgroundResource(R.drawable.frame_avatar2_bg);
				} else if (entry4.getAvatar_mode() == 3) {
					userAvatar4.setImageResource(R.drawable.frame_avatar3_lock);
					userAvatarBg4.setBackgroundResource(R.drawable.frame_avatar1_bg);
				} else if (entry4.getAvatar_mode() == 4) {
					userAvatar4.setImageResource(R.drawable.frame_avatar4_add);
					userAvatarBg4.setBackgroundResource(R.drawable.frame_avatar1_bg);
				}
			} 
		} else {
			contentView.findViewById(R.id.user_space_useravatar4_layout).setVisibility(View.INVISIBLE);
		}
		
	}
	
	private void updateIntegral() {
		if (entry == null) {
			return;
		}
		try {
			tvCreateAndExp.setText(entry.getCredit() + "/" + entry.getExp());
			tvTTCreateAndTTExp.setText(entry.getTtcredit() + "/" + entry.getTtexp());
			tvLevel.setText(entry.getLevel());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private void updateExchange() {
		if (entry == null) {
			return;
		}
		if (space_type != 3) {
			btnAddFriend.setVisibility(View.VISIBLE);
			if (entry.getFriend_show() == 0) {
				btnAddFriend.setVisibility(View.GONE);
			} else if (entry.getFriend_show() == 1) {
				btnAddFriend.setBackgroundResource(R.drawable.btn_blue_try);
				btnAddFriend.setText(getString(R.string.user_space_bottle_addfriend));
			} else if (entry.getFriend_show() == 2) {
				btnAddFriend.setBackgroundResource(R.drawable.btn_red_try);
				btnAddFriend.setText(getString(R.string.user_space_bottle_addfriend));
			} else {
				btnAddFriend.setBackgroundResource(R.drawable.btn_gray_try);
				btnAddFriend.setText(getString(R.string.user_space_bottle_delfriend));
			}
			btnExPhoto.setVisibility(View.VISIBLE);
			if (entry.getPicex_show() == 0) {
				btnExPhoto.setVisibility(View.GONE);
			} else if (entry.getPicex_show() == 1) {
				btnExPhoto.setBackgroundResource(R.drawable.btn_blue_try);
			} else {
				btnExPhoto.setBackgroundResource(R.drawable.btn_red_try);
			}
			btnExProfile.setVisibility(View.VISIBLE);
			if (entry.getInfoex_show() == 0) {
				btnExProfile.setVisibility(View.GONE);
			} else if (entry.getInfoex_show() == 1) {
				btnExProfile.setVisibility(View.VISIBLE);
				btnExProfile.setBackgroundResource(R.drawable.btn_blue_try);
			} else {
				btnExProfile.setBackgroundResource(R.drawable.btn_red_try);
			}
			btnBlacklist.setVisibility(View.VISIBLE);
			if (entry.getBlacklist_show() == 0) {
				btnBlacklist.setVisibility(View.GONE);
			} else if (entry.getBlacklist_show() == 1) {
				btnBlacklist.setVisibility(View.VISIBLE);
				btnBlacklist.setBackgroundResource(R.drawable.btn_gray_try);
				btnBlacklist.setText(getString(R.string.user_space_bottle_addblacklist));
			} else {
				btnBlacklist.setBackgroundResource(R.drawable.button_black);
				btnBlacklist.setText(getString(R.string.user_space_bottle_delblacklist));
			}
			
		}
	}

	@SuppressLint("ResourceAsColor")
	private void updateFeeds() {
		bodyLayout.removeAllViews();
		if (space_type == 0 || space_type == 3) {
			btnNewsfeeds.setVisibility(View.VISIBLE);
		} else {
			btnNewsfeeds.setVisibility(View.GONE);
		}
		if (selectType == 0) {
			btnNewsfeeds.setBackgroundResource(R.drawable.botton_white);
			btnNewsfeeds.setTextColor(R.color.gray);
			btnBottlefeeds.setBackgroundResource(0);
			btnBottlefeeds.setTextColor(Color.WHITE);
			btnProfile.setTextColor(Color.WHITE);
			btnProfile.setBackgroundResource(0);
			newsAdapter = new NewsFeedAdapter();
			listView.setAdapter(newsAdapter);
		} else if (selectType == 1) {
			btnNewsfeeds.setTextColor(Color.WHITE);
			btnNewsfeeds.setBackgroundResource(0);
			btnBottlefeeds.setBackgroundResource(R.drawable.botton_white);
			btnBottlefeeds.setTextColor(R.color.gray);
			btnProfile.setTextColor(Color.WHITE);
			btnProfile.setBackgroundResource(0);
			bottlesAdapter = new BottlesFeedAdapter();
			listView.setAdapter(bottlesAdapter);
		} else {
			listView.setAdapter(new ProfileAdapter());
			btnNewsfeeds.setBackgroundResource(0);
			btnNewsfeeds.setTextColor(Color.WHITE);
			btnBottlefeeds.setTextColor(Color.WHITE);
			btnBottlefeeds.setBackgroundResource(0);
			btnProfile.setBackgroundResource(R.drawable.botton_white);
			btnProfile.setTextColor(R.color.gray);
			updateProfile();
		}
	}
	
	private void updateProfile() {
		View view = LayoutInflater.from(this).inflate(R.layout.user_info_detail, null);
		TextView hometownView = (TextView) view.findViewById(R.id.user_info_hometown);
		TextView workcityView = (TextView) view.findViewById(R.id.user_info_workcity);
		TextView residecityView = (TextView) view.findViewById(R.id.user_info_reside_city);
		TextView birthdayView = (TextView) view.findViewById(R.id.user_info_birthday);
		TextView bloodtypeView = (TextView) view.findViewById(R.id.user_info_blood_type);
		TextView statusView = (TextView) view.findViewById(R.id.user_info_status);
		TextView educationView = (TextView) view.findViewById(R.id.user_info_education_status);
		TextView workView = (TextView) view.findViewById(R.id.user_info_company);
		TextView schoolView = (TextView) view.findViewById(R.id.user_info_school);
		TextView careerView = (TextView) view.findViewById(R.id.user_info_career);
		btnInfoExchange = (Button) view.findViewById(R.id.user_info_excange);
		btnInfoExchange.setOnClickListener(this);
		
		if (profileEntry == null) {
			return;
		}
		if (TextUtil.notEmpty(profileEntry.getResidecity())) {
			((LinearLayout) view.findViewById(R.id.user_info_reside_city_layout)).setVisibility(View.VISIBLE);
			residecityView.setText(profileEntry.getResidecity());
		} else {
			((LinearLayout) view.findViewById(R.id.user_info_reside_city_layout)).setVisibility(View.GONE);
		}
		if (profileEntry.getInfo_visible() == 0) {
			btnInfoExchange.setVisibility(View.VISIBLE);
			view.findViewById(R.id.user_info_detail_layout2).setVisibility(View.GONE);
		} else {
			btnInfoExchange.setVisibility(View.GONE);
			view.findViewById(R.id.user_info_detail_layout2).setVisibility(View.VISIBLE);
			if (TextUtil.notEmpty(profileEntry.getWorkcity())) {
				((LinearLayout) view.findViewById(R.id.user_info_workcity_layout)).setVisibility(View.VISIBLE);
				workcityView.setText(profileEntry.getWorkcity());
			} else {
				((LinearLayout) view.findViewById(R.id.user_info_workcity_layout)).setVisibility(View.GONE);
			}
			if (TextUtil.notEmpty(profileEntry.getHometown())) {
				((LinearLayout) view.findViewById(R.id.user_info_hometown_layout)).setVisibility(View.VISIBLE);
				hometownView.setText(profileEntry.getHometown());
			} else {
				((LinearLayout) view.findViewById(R.id.user_info_hometown_layout)).setVisibility(View.GONE);
			}
			if (TextUtil.notEmpty(profileEntry.getBirthday())) {
				((LinearLayout) view.findViewById(R.id.user_info_birthday_layout)).setVisibility(View.VISIBLE);
				birthdayView.setText(profileEntry.getBirthday());
			} else {
				((LinearLayout) view.findViewById(R.id.user_info_birthday_layout)).setVisibility(View.GONE);
			}
			if (TextUtil.notEmpty(profileEntry.getBlood())) {
				((LinearLayout) view.findViewById(R.id.user_info_blood_type_layout)).setVisibility(View.VISIBLE);
				bloodtypeView.setText(profileEntry.getBlood());
			} else {
				((LinearLayout) view.findViewById(R.id.user_info_blood_type_layout)).setVisibility(View.GONE);
			}
			if (TextUtil.notEmpty(profileEntry.getMarriagestatus())) {
				((LinearLayout) view.findViewById(R.id.user_info_status_layout)).setVisibility(View.VISIBLE);
				statusView.setText(profileEntry.getMarriagestatus());
			} else {
				((LinearLayout) view.findViewById(R.id.user_info_status_layout)).setVisibility(View.GONE);
			}
//			if (TextUtil.notEmpty(profileEntry.getResidecity())) {
//				((LinearLayout) findViewById(R.id.user_info_reside_city_layout)).setVisibility(View.VISIBLE);
//				residecityView.setText(profileEntry.getResidecity());
//			} else {
//				((LinearLayout) view.findViewById(R.id.user_info_reside_city_layout)).setVisibility(View.GONE);
//			}
			if (TextUtil.notEmpty(profileEntry.getEdustatus())) {
				((LinearLayout) view.findViewById(R.id.user_info_education_status_layout)).setVisibility(View.VISIBLE);
				educationView.setText(profileEntry.getEdustatus());
			} else {
				((LinearLayout) view.findViewById(R.id.user_info_education_status_layout)).setVisibility(View.GONE);
			}
			if (TextUtil.notEmpty(profileEntry.getCompany())) {
				((LinearLayout) view.findViewById(R.id.user_info_company_layout)).setVisibility(View.VISIBLE);
				workView.setText(profileEntry.getCompany());
			} else {
				((LinearLayout) view.findViewById(R.id.user_info_company_layout)).setVisibility(View.GONE);
			}
			if (TextUtil.notEmpty(profileEntry.getSchool())) {
				((LinearLayout) view.findViewById(R.id.user_info_school_layout)).setVisibility(View.VISIBLE);
				schoolView.setText(profileEntry.getSchool());
			} else {
				((LinearLayout) view.findViewById(R.id.user_info_school_layout)).setVisibility(View.GONE);
			}
			if (TextUtil.notEmpty(profileEntry.getCareer())) {
				((LinearLayout) view.findViewById(R.id.user_info_career_layout)).setVisibility(View.VISIBLE);
				careerView.setText(profileEntry.getCareer());
			} else {
				((LinearLayout) view.findViewById(R.id.user_info_career_layout)).setVisibility(View.GONE);
			}
		}
		bodyLayout.addView(view);
	}
	
	@Override
	public void onClick(View v) {
		if (v == backView) {
			finish();
		} else if (v == homeView) {
			Intent intent = new Intent(this, HomeActivity.class);
			intent.putExtra("currentItem", 1);
			startActivity(intent);
		} else if (v == editMemoView) {
			Intent intent = new Intent(this, ExpandEditActivity.class);
			Bundle extras = new Bundle();
			extras.putString("from_type", AppContext.EDIT_MEMO);
			extras.putString("memo", entry.getMemo());
			extras.putInt("ouid", ouid);
			intent.putExtras(extras);
			startActivity(intent);
		} else if (v == titleView) {
			if (space_type == 0) {
				doSelectGroupAction();
			}
		} else if (v == btnNewsfeeds) {
			selectType = 0;
			if (friendFeedList == null) {
				UICore.eventTask(this, this, get_newsfeeds, "", null);
			} else {
				updateFeeds();
			}
		} else if (v == btnBottlefeeds) {
			selectType = 1;
			if (bottleFeedList == null) {
				UICore.eventTask(this, this, get_bottlefeeds, "", null);
			} else {
				updateFeeds();
			}
		} else if (v == btnProfile) {
			selectType = 2;
			if (profileEntry == null) {
				UICore.eventTask(this, this, get_profile, "", null);
			} else {
				updateFeeds();
			}
		} else if (v == menuView) {
			doBlueJuhuaMenuAction();
		}
//		else if (v == settingView) {
//			Intent intentSetting = new Intent(this, SettingActivity.class);
//			startActivity(intentSetting);
//		} 
		else if (v == btnExchange) {
			LoginUserInfoTable userTable = new LoginUserInfoTable();
			LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
			if (userEntry.getBasicinfo_fullfill() == 0) {
				handler.sendEmptyMessage(user_baseinfo_notfull);
			} else {
				Intent intent = new Intent(this, ExpandEditActivity.class);
				Bundle extras = new Bundle();
				extras.putString("from_type", AppContext.REPLY_INFOEX);
				extras.putString("reply_infoex_type", "apply");
				extras.putInt("ouid", ouid);
				intent.putExtras(extras);
				startActivity(intent);
			}
		} else if (v == btnInfoExchange) {
			LoginUserInfoTable userTable = new LoginUserInfoTable();
			LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
			if (userEntry.getBasicinfo_fullfill() == 0) {
				handler.sendEmptyMessage(user_baseinfo_notfull);
			} else {
				Intent intent = new Intent(this, ExpandEditActivity.class);
				Bundle extras = new Bundle();
				extras.putString("from_type", AppContext.REPLY_INFOEX);
				extras.putString("reply_infoex_type", "apply");
				extras.putInt("ouid", ouid);
				intent.putExtras(extras);
				startActivity(intent);
			}
		} else if (v == avatarView) {
			if (entry.getInfo_visible() == 1) {
				byte[] tempBytes = null;
				try {
					tempBytes = ServiceUtils.BitmapTobytes(bitmap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				Intent bigPicIntent = new Intent(this,PhotoDetailActivity.class);
				bigPicIntent.putExtra("pic_big", entry.getAvatar());
				bigPicIntent.putExtra("thumbnail", tempBytes);
				startActivity(bigPicIntent);
			}
		} else if (v == btnAddFriend) {
//			if (entry.getFriend_show() == 1) {
//				Intent intent = new Intent(this, ExpandEditActivity.class);
//				Bundle extras = new Bundle();
//				extras.putString("from_type", AppContext.APPLY_FRIEND);
//				extras.putInt("ouid", ouid);
//				intent.putExtras(extras);
//				startActivity(intent);
//			} else if (entry.getFriend_show() == 2) {
//				refresh_type = 1;
//				handler.sendEmptyMessage(add_friend_success);
//			} else if (entry.getFriend_show() == 3) {
//				showChoseMes(getString(R.string.user_space_delete_from_tips), cancel_friend);
//			}
			if (entry.getFriend_show() == 1 || entry.getFriend_show() == 2) {
				UICore.eventTask(this, this, EXEU_CHECK_FRIEND, "", null);
			} else {
				showChoseMes(getString(R.string.user_space_delete_from_tips), cancel_friend);
			}
		} else if (v == btnExProfile) {
			refresh_type = 1;
			if (entry.getInfoex_show() == 1) {
				Intent intent = new Intent(this, ExchangeInfoDetailActivity .class);
				intent.putExtra("ouid", ouid);
				intent.putExtra("page", 1);
				startActivity(intent);
			} else if (entry.getInfoex_show() == 2) {
				Intent intentProfile = new Intent(this, ExpandEditActivity.class);
				Bundle bundleProfile = new Bundle();
				bundleProfile.putString("from_type", AppContext.REPLY_INFOEX);
				bundleProfile.putInt("ouid", ouid);
				bundleProfile.putString("reply_infoex_type", "apply");
				intentProfile.putExtras(bundleProfile);
				startActivity(intentProfile);
			}
		} else if (v == btnExPhoto) {
			refresh_type = 1;
			if (entry.getPicex_show() == 1) {
				Intent intent = new Intent(this, ExchangePicDetailActivity.class);
				intent.putExtra("ouid", ouid);
				intent.putExtra("page", 1);
				startActivity(intent);
			} else if (entry.getPicex_show() == 2) {
				Intent intentPhoto = new Intent(this, ExpandEditActivity.class);
				Bundle bundlePhoto = new Bundle();
				bundlePhoto.putString("from_type", AppContext.APPLY_PICEX);
				bundlePhoto.putInt("ouid", ouid);
				intentPhoto.putExtras(bundlePhoto);
				startActivity(intentPhoto);
			}
		} else if (v == btnBlacklist) {
			refresh_type = 1;
			if (entry.getBlacklist_show() == 1) {
				UICore.eventTask(this, this, set_blacklist, "", 1);
			} else if (entry.getBlacklist_show() == 2) {
				UICore.eventTask(this, this, set_blacklist, "", 0);
			}
		} else if (v == userAvatar1) {
			clickOnAvatarListEvent(entry1);
		} else if (v == userAvatar2) {
			clickOnAvatarListEvent(entry2);
		} else if (v == userAvatar3) {
			clickOnAvatarListEvent(entry3);
		} else if (v == userAvatar4) {
			clickOnAvatarListEvent(entry4);
		} else if (v == upgrade) {
			Intent intent = new Intent(this, BtFriendLevelActivity.class);
			intent.putExtra("ouid", ouid);
			startActivity(intent);
		}
	}
	
	private void clickOnAvatarListEvent(AvatarEntry avatarEntry) {
		refresh_type = 2;
		if (space_type == 3) {
			String choices[] = null;
			if (avatarEntry != null && avatarEntry.getAvatar_mode() == 1) {
				choices = new String[3];
				choices[0] = getString(R.string.user_space_bottle_view_avatar);
				choices[1] = getString(R.string.expand_edit_take_photo); // 拍照
				choices[2] = getString(R.string.expand_edit_choose_photo); // 从相册中选择
			} else if (avatarEntry != null && avatarEntry.getAvatar_mode() == 2){
				choices = new String[4];
				choices[0] = getString(R.string.user_space_bottle_view_avatar);
				choices[1] = getString(R.string.user_space_bottle_set_default_avatar);
				choices[2] = getString(R.string.expand_edit_take_photo); // 拍照
				choices[3] = getString(R.string.expand_edit_choose_photo); // 从相册中选择
			} else if (avatarEntry != null && avatarEntry.getAvatar_mode() == 4) {
				choices = new String[2];
				choices[0] = getString(R.string.expand_edit_take_photo);
				choices[1] = getString(R.string.expand_edit_choose_photo); 
			} else {
				choices = new String[2];
				choices[0] = getString(R.string.expand_edit_take_photo);
				choices[1] = getString(R.string.expand_edit_choose_photo); 
			}
			chooseAction(choices, avatarEntry);
		} else {
			if (avatarEntry != null && avatarEntry.getAvatar_mode() == 3) {
				LoginUserInfoTable userTable = new LoginUserInfoTable();
				LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
				if (userEntry.getBasicinfo_fullfill() == 0) {
					handler.sendEmptyMessage(user_baseinfo_notfull);
				} else {
					Intent intent = new Intent(this, ExpandEditActivity.class);
					Bundle extras = new Bundle();
					extras.putString("from_type", AppContext.REPLY_INFOEX);
					extras.putString("reply_infoex_type", "apply");
					extras.putInt("ouid", ouid);
					intent.putExtras(extras);
					startActivity(intent);
				}
			} else {
				gotoPhotoDetailActivity(avatarEntry);
			}
		}
	}
	
	private void gotoPhotoDetailActivity(AvatarEntry avatarEntry) {
		byte[] tempBytes = null;
		try {
			String filename = ServiceUtils.convertUrlToFileName(avatarEntry.getAvatar_middlepic());
			tempBytes = ServiceUtils.readStream(new FileInputStream(new File(
					android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.UserAvatarIcon + "/" + filename)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Intent bigPicIntent = new Intent(this, PhotoDetailActivity.class);
		bigPicIntent.putExtra("pic_big", avatarEntry.getAvatar_bigpic());
		bigPicIntent.putExtra("thumbnail", tempBytes);
		startActivity(bigPicIntent);
	}
	
	/***
	 * 好友申请前检测接口
	 */
	private void checkFriendApply() {
		StringBuffer url = new StringBuffer(UrlConfig.check_friendapply);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&ouid=" + ouid);
		ServiceUtils.dout("CheckFriendApply url: " + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("CheckFriendApply results:" + results.toString());
			if (null != results) {
				JSONObject obj = new JSONObject(results);
				JSONObject resultObj = obj.getJSONObject("results");
				int authok = resultObj.getInt("authok");
				String errmsg = resultObj.getString("errmsg");
				int check_result = resultObj.getInt("check_result");
				String msg = resultObj.getString("msg");
				if (authok == 1) {
					Message message = null;
					switch (check_result) {
					case 0:
						message = handler.obtainMessage(EXEU_CAN_NOT_ADD_FRIEND, msg);
						handler.sendMessage(message);
						break;
					case 1:
					    message = handler.obtainMessage(EXEU_CHECK_FRIEND_SUCCESS, msg);
						handler.sendMessage(message);	
						break;
					case 2:
						message = handler.obtainMessage(EXEU_ALLOW_ADD_FRIEND);
						handler.sendMessage(message);
						break;
					default:
						break;
					}

				} else {
					Message message = handler.obtainMessage(EXEU_CHECK_FRIEND_FAILED, errmsg);
					handler.sendMessage(message);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void cancelFriend() {
		refresh_type = 1;
		String url = UrlConfig.cancel_friend;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("ouid", String.valueOf(ouid));
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultobj = obj.getJSONObject("results");
				if (resultobj.getInt("success") == 0) {
					String errormsg = resultobj.getString("errmsg");
					Message msg = Message.obtain(handler, error, errormsg);
					handler.sendMessage(msg);
				} else {
					String successmsg = resultobj.getString("successmsg");
					Message msg = Message.obtain(handler, cancel_friend_success, successmsg);
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void setFriendGroup() {
		String url = UrlConfig.set_friendgroup;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("ouid", String.valueOf(ouid));
		paramsMap.put("groupid", String.valueOf(groupId));
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultobj = obj.getJSONObject("results");
				if (resultobj.getInt("success") == 0) {
					String errormsg = resultobj.getString("errmsg");
					Message msg = Message.obtain(handler, error, errormsg);
					handler.sendMessage(msg);
				} else {
					String successmsg = resultobj.getString("successmsg");
					Message msg = Message.obtain(handler, set_friend_group_success, successmsg);
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void setBlacklist(int optype) {
		String url = UrlConfig.set_blacklist;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("ouid", String.valueOf(ouid));
		paramsMap.put("optype", String.valueOf(optype));
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultobj = obj.getJSONObject("results");
				if (resultobj.getInt("success") == 0) {
					String errormsg = resultobj.getString("errmsg");
					Message msg = Message.obtain(handler, error, errormsg);
					handler.sendMessage(msg);
				} else {
					String successmsg = resultobj.getString("successmsg");
					Message msg = Message.obtain(handler, set_blacklist, successmsg);
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void setDefaultAvatar(int avatarid) {
		String url = UrlConfig.set_default_avatar;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("ouid", String.valueOf(ouid));
		paramsMap.put("avatarid", String.valueOf(avatarid));
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultobj = obj.getJSONObject("results");
				if (resultobj.getInt("success") == 0) {
					String errormsg = resultobj.getString("errmsg");
					Message msg = Message.obtain(handler, error, errormsg);
					handler.sendMessage(msg);
				} else {
					String successmsg = resultobj.getString("successmsg");
					Message msg = Message.obtain(handler, set_default_avatar, successmsg);
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void setAvatar() {
		String url = UrlConfig.set_avatar;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("avatarid", String.valueOf(avatarid));
        try {
            HashMap<String, File> filesMap = new HashMap<String, File>();
            if (picFile != null) {
    			filesMap.put("pic", picFile);
    		}
            String result = HttpUtils.post(url, paramsMap, filesMap);
            JSONObject object = new JSONObject(result);
        	JSONObject resultObj = object.getJSONObject("results");
        	int success = resultObj.getInt("success");
        	if (success == 0) {
        		String errmsg = resultObj.getString("errmsg");
        		Message msg = Message.obtain(handler, error, errmsg);
        		handler.sendMessage(msg);
        	} else {
        		String successmsg = resultObj.getString("successmsg");
				Message msg = Message.obtain(handler, set_avatar, successmsg);
				handler.sendMessage(msg);
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void sysMesPositiveButtonEvent(int what) {
		if (what == cancel_friend) {
			UICore.eventTask(this, this, cancel_friend, "cancel_friend", null);
		} else if (what == exchange_profile) {
			if (entry.getInfoex_show() == 1) {
				Intent intent = new Intent(this, ExchangeInfoDetailActivity .class);
				intent.putExtra("ouid", ouid);
				intent.putExtra("page", 1);
				startActivity(intent);
			} else if (entry.getInfoex_show() == 2) {
				Intent intentProfile = new Intent(this, ExpandEditActivity.class);
				Bundle bundleProfile = new Bundle();
				bundleProfile.putString("from_type", AppContext.REPLY_INFOEX);
				bundleProfile.putInt("ouid", ouid);
				bundleProfile.putString("reply_infoex_type", "apply");
				intentProfile.putExtras(bundleProfile);
				startActivity(intentProfile);
			}
		} else if (what == complete_info) {
			Intent intent = new Intent(this, SettingActivity.class);
			startActivity(intent);
		}
	}
	
	/**
	 * 选择菜单 弹出框
	 * @param choices 显示的菜单
	 */
	public void chooseAction(String[] choices, final AvatarEntry avatarEntry) {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						doSelectChooseEvent(which, avatarEntry);
					}
				});
		builder.create().show();
	}
	
	
	public void doSelectChooseEvent(int which, AvatarEntry avatarEntry) {
		if (avatarEntry == null) {
			return;
		} else {
			avatarid = avatarEntry.getAvatarid();
			if (avatarEntry.getAvatar_mode() == 1) {
				switch (which) {
				case 0:
					gotoPhotoDetailActivity(avatarEntry);
					break;
				case 1:
					doTakePhoto();
					break;
				case 2:
					doPickPhotoFromGallery();
					break;
				default:
					break;
				}
			} else if (avatarEntry.getAvatar_mode() == 2) {
				switch (which) {
				case 0:
					gotoPhotoDetailActivity(avatarEntry);
					break;
				case 1:
					UICore.eventTask(this, this, set_default_avatar, "", avatarEntry.getAvatarid());
					break;
				case 2:
					doTakePhoto();
					break;
				case 3:
					doPickPhotoFromGallery();
					break;
				default:
					break;
				}
			} else if (avatarEntry.getAvatar_mode() == 4) {
				if (which == 0) {
					doTakePhoto();
				} else {
					doPickPhotoFromGallery();
				}
			}
		}
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case get_space_info:
			getSpaceInfo();
			if (entry != null) {
				if (entry.getSpace_type() == 0 || entry.getSpace_type() == 3) {
					selectType = 0;
				} else {
					selectType = 1;
				}
				if (selectType == 0) {
					newsfeedsPage = 1;
					getFriendFeeds();
				} else if (selectType == 1) {
					bottlefeedsPage = 1;
					getBottleFeeds();
				} else {
					getUserProfile();
				}
				handler.sendEmptyMessage(get_space_info_success);
			}
			break;
		case cancel_friend:
			cancelFriend();
			break;
		case set_friend_group:
			setFriendGroup();
			break;
		case get_more_data:
			if (selectType == 0) {
				newsfeedsPage++;
				getMoreFriendFeeds();
			} else if (selectType == 1) {
				bottlefeedsPage++;
				getMoreBottleFeeds();
			} 
			break;
		case get_newsfeeds:
			getFriendFeeds();
			handler.sendEmptyMessage(get_newsfeeds);
			break;
		case get_bottlefeeds:
			getBottleFeeds();
			handler.sendEmptyMessage(get_bottlefeeds);
			break;
		case get_profile:
			getUserProfile();
			handler.sendEmptyMessage(get_profile);
			break;
		case refresh_space_info:
			getSpaceInfo();
			if (selectType == 0) {
				newsfeedsPage = 1;
				getFriendFeeds();
			} else if (selectType == 1) {
				bottlefeedsPage = 1;
				getBottleFeeds();
			} else {
				getUserProfile();
			}
			handler.sendEmptyMessage(get_space_info_success);
			break;
		case set_blacklist:
			try {
				int optype = Integer.parseInt(obj.toString());
				setBlacklist(optype);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case set_avatar:
			try {
				setAvatar();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case set_default_avatar:
			try {
				setDefaultAvatar(Integer.parseInt(obj.toString()));
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case EXEU_CHECK_FRIEND:
			checkFriendApply();
			break;
		default:
			break;
		}
	}
	
	private void getSpaceInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_space_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&ouid=" + ouid);
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				Gson gson = new Gson();
				SpaceInfo info = gson.fromJson(result, SpaceInfo.class);
				if (info.getResults().getAuthok() == 0) {
					Message msg = Message.obtain(handler, error, info.getResults().getErrmsg());
					handler.sendMessage(msg);
				} else {
					entry = info.getSpace_info();
					avatarEntries = entry.getAvatars_list();
					groupList = info.getGroups_list();
					groupNames = new String[groupList.size() + 1];
					groupNames[0] = getString(R.string.setting_group);
					for (int i = 1;i < groupList.size() + 1;i++) {
						groupNames[i] = groupList.get(i - 1).getGroupname();
					}
					bitmap = HttpUtils.getBitmapFromUrl(UserSpaceActivity.this, entry.getAvatar());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private void getUserProfile() {
		StringBuffer url = new StringBuffer(UrlConfig.get_user_profile);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&ouid=" + ouid);
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				Gson gson = new Gson();
				ProfileInfo info = gson.fromJson(result, ProfileInfo.class);
				if (info.getResults().getAuthok() == 0) {
					Message msg = Message.obtain(handler, error, info.getResults().getErrmsg());
					handler.sendMessage(msg);
				} else {
					profileEntry = info.getProfile_info();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getBottleFeeds() {
		StringBuffer url = new StringBuffer(UrlConfig.get_user_btfeedslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&ouid=" + ouid);
		url.append("&count=" + count);
		url.append("&page=" + bottlefeedsPage);
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				Gson gson = new Gson();
				BottleFeedInfo info = gson.fromJson(result, BottleFeedInfo.class);
				ResponseResult res = info.getResults();
				if (res.getAuthok() == 1) {
					bottleFeedList = info.getBtfeeds_list();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getFriendFeeds() {
		if (AppContext.getInstance().getLogin_uid() == ouid) {
			ouid = AppContext.getInstance().getLogin_uid();
		}
		StringBuffer url = new StringBuffer(UrlConfig.get_user_feedslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&ouid=" + ouid);
		url.append("&count=" + count);
		url.append("&page=" + newsfeedsPage);
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				Gson gson = new Gson();
				FriendFeedInfo info = gson.fromJson(result, FriendFeedInfo.class);
				ResponseResult res = info.getResults();
				if (res.getAuthok() == 1) {
					friendFeedList = info.getFeeds_list();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getMoreBottleFeeds() {
		StringBuffer url = new StringBuffer(UrlConfig.get_user_btfeedslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&ouid=" + ouid);
		url.append("&count=" + count);
		url.append("&page=" + bottlefeedsPage);
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				Gson gson = new Gson();
				BottleFeedInfo info = gson.fromJson(result, BottleFeedInfo.class);
				ResponseResult res = info.getResults();
				if (res.getAuthok() == 1) {
					moreBottleFeedList = info.getBtfeeds_list();
					if (moreBottleFeedList != null && !moreBottleFeedList.isEmpty()) {
						bottleFeedList.addAll(moreBottleFeedList);
					}
					handler.sendEmptyMessage(get_more_data);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getMoreFriendFeeds() {
		StringBuffer url = new StringBuffer(UrlConfig.get_user_feedslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&ouid=" + ouid);
		url.append("&count=" + count);
		url.append("&page=" + newsfeedsPage);
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				Gson gson = new Gson();
				FriendFeedInfo info = gson.fromJson(result, FriendFeedInfo.class);
				ResponseResult res = info.getResults();
				if (res.getAuthok() == 1) {
					moreFriendFeedList = info.getFeeds_list();
					if (moreFriendFeedList != null && !moreFriendFeedList.isEmpty()) {
						friendFeedList.addAll(moreFriendFeedList);
					}
					handler.sendEmptyMessage(get_more_data);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void doSelectGroupAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, groupNames);
	
		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(getString(R.string.choose_friend_select_group));
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						groupItem = which;
						if (which != 0) {
							groupId = groupList.get(which - 1).getGroupid();
							UICore.eventTask(UserSpaceActivity.this,
									UserSpaceActivity.this, set_friend_group, "set_friend_group", null);
						} else {
							Intent intent = new Intent(UserSpaceActivity.this, ManagerGroupActivity.class);
							startActivity(intent);
						}
						
					}
				});
		builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
			
		});
		builder.create().show();
	}
	
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case error:
			onToast((String) msg.obj);
			break;
		case get_space_info_success:
			updateUI();
			listView.onRefreshComplete();
			break;
		case set_friend_group_success:
			onToast((String) msg.obj);
			titleView.setText(getString(R.string.user_space_friend) + "(" + groupNames[groupItem] + ")");
			break;
		case get_more_data:
			loadMoreView.setVisibility(View.GONE);
//			progressBar.setVisibility(View.GONE);
//			loadMoreView.setText(getString(R.string.more_data));
			if (selectType == 0) {
				newsAdapter.notifyDataSetChanged();
				listView.setSelection(newsAdapter.getCount() - count);
			} else if (selectType == 1) {
				bottlesAdapter.notifyDataSetChanged();
				listView.setSelection(bottlesAdapter.getCount() - count);
			} 
			break;
		case cancel_friend_success:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, refresh_space_info, "get_space_info", null);
			break;
		case add_friend_success:
			UICore.eventTask(this, this, refresh_space_info, "get_space_info", null);
			break;
		case check_friend_error:
			onToast((String) msg.obj);
			break;
		case refresh_space_info:
			if (refresh_type == 1) {
				updateExchange();
			} else if (refresh_type == 2) {
				updateAvatarList();
			}
			break;
		case set_blacklist:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, refresh_space_info, "get_space_info", null);
			break;
		case set_avatar:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, get_space_info, "get_space_info", null);
			break;
		case view_album_error:
			onToast(getString(R.string.exchange_feed_invisible_tips));
			break;
		case user_baseinfo_notfull:
			LoginUserInfoTable userTable = new LoginUserInfoTable();
			LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
			showChoseMes(userEntry.getBasicinfo_tip(), complete_info);
			break;
		case set_default_avatar:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, get_space_info, "get_space_info", null);
			break;
		case get_newsfeeds:
			updateFeeds();
			break;
		case get_bottlefeeds:
			updateFeeds();
			break;
		case get_profile:
			updateFeeds();
			break;
		case EXEU_CHECK_FRIEND_FAILED:
			onToast((String) msg.obj);
			break;
		case EXEU_CAN_NOT_ADD_FRIEND:
			onToast((String) msg.obj);
			break;
		case EXEU_CHECK_FRIEND_SUCCESS:
			onToast((String) msg.obj);
			Intent userIntent = new Intent(this, UserSpaceActivity.class);
			userIntent.putExtra("ouid", ouid);
			startActivity(userIntent);
			break;
		case EXEU_ALLOW_ADD_FRIEND:
			Intent applyIntent = new Intent(this, ExpandEditActivity.class);
			Bundle bundleFriend = new Bundle();
			bundleFriend.putString("from_type", AppContext.APPLY_FRIEND);
			bundleFriend.putInt("ouid", ouid);
			applyIntent.putExtras(bundleFriend);
			startActivity(applyIntent);
			break;
		default:
			break;
		}
		return false;
	}

	
//	public class NewsFeedsView extends LinearLayout {
//		
//		private View convertView;
//		private FriendFeedEntry entry;
//		private String choices[];
//		
//		public NewsFeedsView(Context context, FriendFeedEntry entry) {
//			super(context);
//			this.entry = entry;
//			initWidget();
//			addView(convertView);
//			setOrientation(LinearLayout.VERTICAL);
//			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
//			params.topMargin = 5;
//			ImageView image = new ImageView(context);
//			image.setBackgroundResource(R.drawable.line_gray);
//			addView(image);
//		}
//
//		public NewsFeedsView(Context context, AttributeSet attrs) {
//			super(context, attrs);
//		}
//		
//		private void initWidget() {
//			try {
//				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.friend_feed_listitem, null);
//				TextView content = (TextView) convertView.findViewById(R.id.feed_content);
//				TextView timeView = (TextView) convertView.findViewById(R.id.feed_time);
//				RemoteImageView avatar = (RemoteImageView) convertView.findViewById(R.id.avatar);
//				RemoteImageView image = (RemoteImageView) convertView.findViewById(R.id.feed_image);
//				((ImageView) convertView.findViewById(R.id.iv_white)).setVisibility(View.GONE);
//				if (entry != null) {
//					avatar.setDefaultImage(R.drawable.avatar_default_big);
//					avatar.setImagePath(entry.getFeed_avatar(), AppContext.UserAvatarIcon);
//					String nickname = "<font color=#419AD9>"+entry.getFeed_nickname()+"</font>";
//					content.setText(Html.fromHtml(nickname + "&nbsp;" + entry.getFeed_content()));
//					timeView.setText((!TextUtils.isEmpty(entry.getFeed_time()))?("#"+entry.getFeed_time()):"");
//					this.setOnClickListener(new View.OnClickListener() {
//						
//						@Override
//						public void onClick(View v) {
//							if (TextUtil.notEmpty(entry.getFeed_smallpic())) {
//								if (TextUtil.notEmpty(entry.getFeed_related_nickname())) {
//									choices = new String[2];
//									choices[0] = getString(R.string.user_space_bottle_view_photo);
//									choices[1] = getString(R.string.user_info_view) + entry.getFeed_related_nickname() + getString(R.string.user_info_space);
//									chooseAction(choices, entry);
//								}
//							} else {
//								if (TextUtil.notEmpty(entry.getFeed_related_nickname())) {
//									choices = new String[1];
//									choices[0] = getString(R.string.user_info_view) + entry.getFeed_related_nickname() + getString(R.string.user_info_space);
//									chooseAction(choices, entry);
//								}
//							}
//						}
//					});
//					if (TextUtil.notEmpty(entry.getFeed_smallpic())) {
//						image.setDefaultImage(R.drawable.album_nophoto);
//						image.setImagePath(entry.getFeed_smallpic(), AppContext.BottleTimelineIcon);
//						image.setVisibility(View.VISIBLE);
//						((RelativeLayout) convertView.findViewById(R.id.rl_bottle_content_photo)).setVisibility(View.VISIBLE);
//					} else {
//						((RelativeLayout) convertView.findViewById(R.id.rl_bottle_content_photo)).setVisibility(View.GONE);
//					}
//					avatar.setOnClickListener(new View.OnClickListener() {
//						
//						@Override
//						public void onClick(View v) {
//							Intent spaceIntent = new Intent(UserSpaceActivity.this, UserSpaceActivity.class);
//							spaceIntent.putExtra("ouid", entry.getFeed_uid());
//							startActivity(spaceIntent);
//						}
//					});
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			
//		}
//		
//	}
	
	public class NewsFeedAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return friendFeedList == null ? 0 : friendFeedList.size();
		}

		@Override
		public Object getItem(int position) {
			return friendFeedList == null ? null : friendFeedList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
//			if (position == getCount() - 1) {
//				View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.listfooter_more, null);
////				progressBar = (ProgressBar) view.findViewById(R.id.pull_to_refresh_progress);
//				loadMoreView = (TextView) view.findViewById(R.id.load_more);
//				if (getCount() >= count) {
//					view.setVisibility(View.VISIBLE);
//				} else {
//					view.setVisibility(View.INVISIBLE);
//				}
//				return view;
//			}
			NewsFeedViewHolder holder = null;
			if (convertView != null  && convertView.getId() == R.id.friend_feed_listitem_layout) {
				holder = (NewsFeedViewHolder) convertView.getTag();
			} else {
				holder = new NewsFeedViewHolder();
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.friend_feed_listitem, null);
				holder.content = (TextView) convertView.findViewById(R.id.feed_content);
				holder.timeView = (TextView) convertView.findViewById(R.id.feed_time);
				holder.avatar = (RemoteImageView) convertView.findViewById(R.id.avatar);
				holder.image = (RemoteImageView) convertView.findViewById(R.id.feed_image);
				convertView.setTag(holder);
			}
			try {
				final FriendFeedEntry entry = friendFeedList.get(position);
				if (entry != null) {
					holder.avatar.setDefaultImage(R.drawable.avatar_default_big);
					holder.avatar.setImagePath(entry.getFeed_avatar());
					String nickname = "<font color=#419AD9>"+entry.getFeed_nickname()+"</font>";
					holder.content.setText(Html.fromHtml(nickname + "&nbsp;" + entry.getFeed_content()));
					holder.timeView.setText((!TextUtils.isEmpty(entry.getFeed_time()))?("#"+entry.getFeed_time()):"");
					if (TextUtil.notEmpty(entry.getFeed_smallpic())) {
						loader.DisplayImage(entry.getFeed_smallpic(), holder.image, R.drawable.album_nophoto);
						holder.image.setVisibility(View.VISIBLE);
						((RelativeLayout) convertView.findViewById(R.id.rl_bottle_content_photo)).setVisibility(View.VISIBLE);
					} else {
						((RelativeLayout) convertView.findViewById(R.id.rl_bottle_content_photo)).setVisibility(View.GONE);
					}
					holder.avatar.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							Intent spaceIntent = new Intent(UserSpaceActivity.this, UserSpaceActivity.class);
							spaceIntent.putExtra("ouid", entry.getFeed_uid());
							startActivity(spaceIntent);
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}
		
	}

	public static class NewsFeedViewHolder {
		TextView content;
		TextView timeView;
		RemoteImageView avatar;
		RemoteImageView image;
	}
	
//	public class BottleFeedsView extends LinearLayout {
//		
//		private View convertView;
//		private SpaceBottleFeedEntry entry;
//		
//		public BottleFeedsView(Context context, SpaceBottleFeedEntry entry) {
//			super(context);
//			this.entry = entry;
//			initWidget();
//			setOrientation(LinearLayout.VERTICAL);
//			addView(convertView);
//			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
//			params.topMargin = 5;
//			ImageView image = new ImageView(context);
//			image.setBackgroundResource(R.drawable.line_gray);
//			addView(image);
//		}
//
//		public BottleFeedsView(Context context, AttributeSet attrs) {
//			super(context, attrs);
//		}
//		
//		private void initWidget() {
//			try {
//				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bottle_feed_listitem, null);
//				TextView content = (TextView) convertView.findViewById(R.id.feed_content);
//				TextView time_location = (TextView) convertView.findViewById(R.id.feed_time_location);
//				RemoteImageView avatar = (RemoteImageView) convertView.findViewById(R.id.avatar);
//				((ImageView) convertView.findViewById(R.id.iv_white)).setVisibility(View.GONE);
//				if (entry != null) {
//					avatar.setDefaultImage(R.drawable.avatar_default_big);
//					avatar.setImagePath(entry.getBtfeed_avatar(), AppContext.UserAvatarIcon);
//					String nickname = "<font color=#666666>"+entry.getBtfeed_nickname()+"</font>";
//					content.setText(Html.fromHtml(nickname + "&nbsp;" + entry.getBtfeed_content()));
//					String time = (!TextUtils.isEmpty(entry.getBtfeed_time()))?("#"+entry.getBtfeed_time()):"";
//					String location = (!TextUtils.isEmpty(entry.getBtfeed_location()))?("@"+entry.getBtfeed_location()):"";
//					time_location.setText(Html.fromHtml(time + " " + location));
//				}
//				convertView.setOnClickListener(new View.OnClickListener() {
//					
//					@Override
//					public void onClick(View v) {
//						Intent intent = new Intent(UserSpaceActivity.this, BottleSingleActivity.class);
//						intent.putExtra("btid", entry.getBtid());
//						startActivity(intent);
//					}
//				});
//				avatar.setOnClickListener(new View.OnClickListener() {
//					
//					@Override
//					public void onClick(View v) {
//						Intent spaceIntent = new Intent(UserSpaceActivity.this, UserSpaceActivity.class);
//						spaceIntent.putExtra("ouid", entry.getBtfeed_uid());
//						startActivity(spaceIntent);
//					}
//				});
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//		
//	}
	
	public class BottlesFeedAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return bottleFeedList == null ? 0 : bottleFeedList.size();
		}

		@Override
		public Object getItem(int position) {
			return bottleFeedList == null ? 0 : bottleFeedList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
//			if (position == getCount() - 1) {
//				View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.listfooter_more, null);
//				progressBar = (ProgressBar) view.findViewById(R.id.pull_to_refresh_progress);
//				loadMoreView = (TextView) view.findViewById(R.id.load_more);
//				if (getCount() >= count) {
//					view.setVisibility(View.VISIBLE);
//				} else {
//					view.setVisibility(View.INVISIBLE);
//				}
//				return view;
//			}
			BottlesFeedViewHolder holder = null;
			if (convertView != null && convertView.getId() == R.id.bottle_feed_listitem_layout) {
				holder = (BottlesFeedViewHolder) convertView.getTag();
			} else {
				holder = new BottlesFeedViewHolder();
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bottle_feed_listitem, null);
				holder.content = (TextView) convertView.findViewById(R.id.feed_content);
				holder.time_location = (TextView) convertView.findViewById(R.id.feed_time_location);
				holder.avatar = (RemoteImageView) convertView.findViewById(R.id.avatar);
				convertView.setTag(holder);
			}
			try {
				final SpaceBottleFeedEntry entry = bottleFeedList.get(position);
				if (entry != null) {
					holder.avatar.setDefaultImage(R.drawable.avatar_default_big);
					holder.avatar.setImagePath(entry.getBtfeed_avatar());
					String nickname = "<font color=#666666>"+entry.getBtfeed_nickname()+"</font>";
					holder.content.setText(Html.fromHtml(nickname + "&nbsp;" + entry.getBtfeed_content()));
					String time = (!TextUtils.isEmpty(entry.getBtfeed_time()))?("#"+entry.getBtfeed_time()):"";
					String location = (!TextUtils.isEmpty(entry.getBtfeed_location()))?("@"+entry.getBtfeed_location()):"";
					holder.time_location.setText(Html.fromHtml(time + " " + location));
				}
				holder.avatar.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent spaceIntent = new Intent(UserSpaceActivity.this, UserSpaceActivity.class);
						spaceIntent.putExtra("ouid", entry.getBtfeed_uid());
						startActivity(spaceIntent);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}
		
	}
	
	public static class BottlesFeedViewHolder {
		TextView content;
		TextView time_location;
		RemoteImageView avatar;
	}
	
	public class ProfileAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return convertView;
		}
		
	}
	
	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
		    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		    File pictureFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
            if (!pictureFileDir.exists()) {
                pictureFileDir.mkdirs();
            }
            picFile = new File(pictureFileDir, "upload.jpeg");
            Uri pictureUri = Uri.fromFile(picFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
            startActivityForResult(cameraIntent, activity_result_camara_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 从本地手机中选择图片
	 */
//	private void doSelectImageFromLoacal(){
//		Intent localIntent = new Intent();
//		localIntent.setType("image/*");
//		localIntent.setAction("android.intent.action.GET_CONTENT");
//        Intent localIntent2 = Intent.createChooser(localIntent, getString(R.string.expand_edit_choose_photo));
//        startActivityForResult(localIntent2, activity_result_pick_with_data);
//	}
	
	// 封装请求Gallery的intent
	public Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		return intent;
	}
	
	// 请求Gallery程序
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, activity_result_pick_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	protected void doCropPhoto(File f) {
		try {
			// 启动gallery去剪辑这个照片
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, activity_result_pick_with_data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	* Constructs an intent for image cropping. 调用图片剪辑程序
	*/
	public Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		return intent;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Bitmap oldBitmap = bitMap;
		switch (requestCode) {
		case activity_result_pick_with_data: //从本地选择图片
			if (data == null) {
				return;
			}
			bitMap = data.getParcelableExtra("data");
            try {
                File pictureFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
                if (!pictureFileDir.exists()) {
                    pictureFileDir.mkdirs();
                }
                picFile = new File(pictureFileDir, "upload.jpeg");
                FileOutputStream ous = new FileOutputStream(picFile);
                bitMap.compress(Bitmap.CompressFormat.JPEG, 100, ous);
              
            	if ( !Utility.isExternalStorageAvilable() ) {
    				return;
    			}
    			Uri fileUri = Uri.fromFile(picFile);
    			Intent newIntent = new Intent( this, FeatherActivity.class );
    			newIntent.putExtra( "From_Type", Constants.ACTIVITY_AVATAR );
    			newIntent.setData( fileUri );
    			newIntent.putExtra( "API_KEY", Utility.API_KEY );

    			newIntent.putExtra( "output", Uri.parse( "file://" + picFile.getAbsolutePath() ) );
    			newIntent.putExtra( Constants.EXTRA_OUTPUT_FORMAT, Bitmap.CompressFormat.JPEG.name() );
    			newIntent.putExtra( Constants.EXTRA_OUTPUT_QUALITY, 100 );
    			newIntent.putExtra( Constants.EXTRA_TOOLS_DISABLE_VIBRATION, true );

    			final DisplayMetrics metrics = new DisplayMetrics();
    			getWindowManager().getDefaultDisplay().getMetrics( metrics );
    			int max_size = Math.min( metrics.widthPixels, metrics.heightPixels );
    			max_size = (int) ( (double) max_size / 0.8 );
    			newIntent.putExtra( "max-image-size", max_size );
    			newIntent.putExtra( "effect-enable-borders", true );
    			startActivityForResult(newIntent, activity_result_aviary );
                
            } catch (Exception e) {
                e.printStackTrace();
            }
			break;
		case activity_result_camara_with_data:  //拍照
			if (picFile == null) {
				File pictureFileDir = new File(
						Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
				picFile = new File(pictureFileDir, "upload.jpeg");
			}
			doCropPhoto(picFile);
			break;
		case activity_result_aviary:
			if (resultCode == RESULT_OK) {
				try {
					File pictureFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
		            if (!pictureFileDir.exists()) {
		                pictureFileDir.mkdirs();
		            }
		            picFile = new File(pictureFileDir, "upload.jpeg");

		            FileInputStream in = new FileInputStream(picFile);
					BitmapFactory.Options options1 = new BitmapFactory.Options();
					options1.inPurgeable = true;
					options1.inInputShareable = true;
					options1.inSampleSize = 2;
					try {
						BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options1, true);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					WeakReference<Bitmap> bitmapResult = new WeakReference<Bitmap>(BitmapFactory
							.decodeStream(in, null, options1));
					Bitmap bt = bitmapResult.get();
		            avatarView.setImageBitmap(bt);
		            UICore.eventTask(this, this, set_avatar, "set_avatar", null);
						
				} catch (Exception e) {
					e.printStackTrace();
				} finally{
				}
	            
			}
		}
	}
	
	private void doBlueJuhuaMenuAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		String choices[] = new String[] {getString(R.string.friend_myfriend), getString(R.string.more_message), getString(R.string.exchange_bt_album)};
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);
	
		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(getString(R.string.system_info));
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							LoginUserInfoTable userTable = new LoginUserInfoTable();
							LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
							if (userEntry.getBasicinfo_fullfill() == 0) {
								handler.sendEmptyMessage(user_baseinfo_notfull);
							} else {
								Intent intent = new Intent(UserSpaceActivity.this, FriendListActivity.class);
								intent.putExtra("ouid", ouid);
								startActivity(intent);
							}
							break;
						case 1:
							if (entry.getSendmsg_mode() == 0) {
								Intent intent = new Intent(UserSpaceActivity.this, MessageListActivity.class);
								intent.putExtra("ouid", ouid);
								startActivity(intent);
							} else if (entry.getSendmsg_mode() == 1) {
								Intent intent = new Intent(UserSpaceActivity.this, ConversationListActivity.class);
								intent.putExtra("ouid", ouid);
								startActivity(intent);
							} else {
								
							}
							break;
						case 2:
							if (entry.getAlbum_visible() == 1) {
								Intent intent = new Intent(UserSpaceActivity.this, AlbumsActivity.class);
								intent.putExtra("ouid", ouid);
								startActivity(intent);
							} else {
								handler.sendEmptyMessage(view_album_error);
							}
							break;
						default:
							break;
						}
						
					}
				});
		builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
			
		});
		builder.create().show();
	}

	/**
	 * 选择菜单 弹出框
	 * @param choices 显示的菜单
	 */
	public void chooseAction(final String[] choices, final FriendFeedEntry feedEntry) {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						doSelectChooseEvent(which, choices, feedEntry);
					}
				});
		builder.create().show();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			File uploadFileDir = new File(
					Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
			File file = new File(uploadFileDir, "upload.jpeg");
			if (file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doSelectChooseEvent(int which, String choics[], FriendFeedEntry feedEntry) {
		if (feedEntry == null) {
			return;
		} else {
			if (choics.length == 2) {
				if (which == 0) {
					Intent intent = new Intent(this, UserPhotoActivity.class);
					intent.putExtra("picid", feedEntry.getFeed_picid());
					startActivity(intent);
				} else {
					Intent intent = new Intent(this, UserSpaceActivity.class);
					intent.putExtra("ouid", feedEntry.getFeed_related_uid());
					startActivity(intent);
				}
			} else {
				if (feedEntry.getFeed_related_uid() != 0) {
					Intent intent = new Intent(this, UserSpaceActivity.class);
					intent.putExtra("ouid", feedEntry.getFeed_related_uid());
					startActivity(intent);
				} else {
					Intent intent = new Intent(this, UserPhotoActivity.class);
					intent.putExtra("picid", feedEntry.getFeed_picid());
					startActivity(intent);
				}
			}
		}
	}
	
}
